/**
 * 工具类
 */

/**
 * 是否隐藏loading
 */
var _hide_loading;

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const timestampToTime = timestamp => {
  var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  var D = date.getDate() + ' ';
  var h = date.getHours() + ':';
  var m = date.getMinutes() + ':';
  var s = date.getSeconds();
  return Y + M + D + h + m + s;
}

// 计算两个经纬度之间的距离
const distance = (la1, lo1, la2, lo2) => {
  var La1 = la1 * Math.PI / 180.0;
  var La2 = la2 * Math.PI / 180.0;
  var La3 = La1 - La2;
  var Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
  s = s * 6378.137; //地球半径
  s = Math.round(s * 10000) / 10000;
  // console.log("计算结果",s)
  return s
}

//计算两个经纬度之间的步行或驾车距离
const calculateDistance = (la1, lo1, la2, lo2) => {
  // 实例化API核心类
  qqmapsdk = new QQMapWX({
    key: 'AD5BZ-CHCKS-64OOD-6G6TX-BSOA6-IFF3V'
  });

  return new Promise(function (resolve, reject) {
    // 调用接口
    let res = qqmapsdk.calculateDistance({
      mode: 'driving',
      from: {
        latitude: la2,
        longitude: lo2
      },
      to: [{
        latitude: la1,
        longitude: lo1
      }],
      success: function (res) {
        resolve(res)
      },
      fail: function (res) {
        reject(res);
      },
      complete: function (res) {

      }
    });
  });
}
//小于10的格式化函数
function timeFormat(param) {
  return param < 10 ? '0' + param : param;
}

//倒计时函数
function countDown(teamBuyTimeList) {
  // 获取当前时间，同时得到活动结束时间数组
  const that = this
  let newTime = new Date().getTime() / 1000;
  let teamBuyTimeInfoList = teamBuyTimeList;
  let countDownArr = [];
  // 对结束时间进行处理渲染到页面
  teamBuyTimeInfoList.forEach(o => {
    // iOS不兼容？
    // let endTime = new Date(o).getTime();   
    // ios 转换时间戳？？？
    let date = o.openTeamTime.substr(0, 10)//2017-02-27
    let hour = o.openTeamTime.substr(11, 2) == '00' ? 0 : o.openTeamTime.substr(11, 2).replace(/\b(0+)/gi, "")
    let minute = o.openTeamTime.substr(14, 2) == '00' ? 0 : o.openTeamTime.substr(14, 2).replace(/\b(0+)/gi, "")
    let second = o.openTeamTime.substr(17, 2) == '00' ? 0 : o.openTeamTime.substr(17, 2).replace(/\b(0+)/gi, "")
    let timestamp = parseInt(new Date(date).getTime() / 1000) + parseInt(o.duration) + parseInt(hour) * 3600 + parseInt(minute) * 60 + parseInt(second) - 28800//别问我为什么-28800，只能告诉你实践出真知                   
    //var endNewTime = timestampFormat(timestamp)//timestampFormat：自定义的将时间戳转换为刚刚，昨天16:42等表达的方法
    let endTime = timestamp
    let obj = null;
    // 如果活动未结束，对时间进行处理
    if (endTime - newTime > 0) {
      let time = (endTime - newTime);
      // 获取天、时、分、秒
      let day = parseInt(time / (60 * 60 * 24));
      let hou = parseInt(time % (60 * 60 * 24) / 3600) + parseInt(day * 24);
      let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
      let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
      obj = {
        day: this.timeFormat(day),
        hou: timeFormat(hou),
        min: timeFormat(min),
        sec: timeFormat(sec)
      }
    } else {//活动已结束，全部设置为'00'
      obj = {
        //day: '00',
        hou: '00',
        min: '00',
        sec: '00'
      }
    }
    countDownArr.push(obj)
  })
  // 渲染，然后每隔一秒执行一次倒计时函数
  return countDownArr
}
//倒计时函数
function countDownDay(teamBuyTimeList) {
  // 获取当前时间，同时得到活动结束时间数组
  const that = this
  let newTime = new Date().getTime() / 1000;
  let teamBuyTimeInfoList = teamBuyTimeList;
  let countDownArr = [];
  // 对结束时间进行处理渲染到页面
  teamBuyTimeInfoList.forEach(o => {
    // iOS不兼容？
    // let endTime = new Date(o).getTime();   
    // ios 转换时间戳？？？
    let date = o.openTeamTime.substr(0, 10)//2017-02-27
    let hour = o.openTeamTime.substr(11, 2) == '00' ? 0 : o.openTeamTime.substr(11, 2).replace(/\b(0+)/gi, "")
    let minute = o.openTeamTime.substr(14, 2) == '00' ? 0 : o.openTeamTime.substr(14, 2).replace(/\b(0+)/gi, "")
    let second = o.openTeamTime.substr(17, 2) == '00' ? 0 : o.openTeamTime.substr(17, 2).replace(/\b(0+)/gi, "")
    let timestamp = parseInt(new Date(date).getTime() / 1000) + parseInt(o.duration) + parseInt(hour) * 3600 + parseInt(minute) * 60 + parseInt(second) - 28800//别问我为什么-28800，只能告诉你实践出真知                   
    //var endNewTime = timestampFormat(timestamp)//timestampFormat：自定义的将时间戳转换为刚刚，昨天16:42等表达的方法
    let endTime = timestamp
    let obj = null;
    // 如果活动未结束，对时间进行处理
    if (endTime - newTime > 0) {
      let time = (endTime - newTime);
      // 获取天、时、分、秒
      let day = parseInt(time / (60 * 60 * 24));
      let hou = parseInt(time % (60 * 60 * 24) / 3600);
      let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
      let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
      obj = {
        day: day,
        hou: timeFormat(hou),
        min: timeFormat(min),
        sec: timeFormat(sec)
      }
    } else {//活动已结束，全部设置为'00'
      obj = {
        day: '00',
        hou: '00',
        min: '00',
        sec: '00'
      }
    }
    countDownArr.push(obj)
  })
  // 渲染，然后每隔一秒执行一次倒计时函数
  return countDownArr
}

// 处理 Access Token 已过期
function handleLoginStatus(error) {
  if (error.code !== 20) {
    wx.showToast({
      title: error.message,
      icon: 'none',
      duration: 2000
    })
  }
}

var numberConversion = {
  /*
      单位
  */
  units: '个十百千万@#%亿^&~',
  /*
      字符
  */
  chars: '零一二三四五六七八九',
  /*
      数字转中文
      @number {Integer} 形如123的数字
      @return {String} 返回转换成的形如 一百二十三 的字符串            
  */
  numberToChinese: function (number) {
    if (number > 999) {
      return '千';
    } else {
      var a = (number + '').split(''),
        s = [],
        t = this;
      if (a.length > 12) {
        throw new Error('too big');
      } else {
        for (var i = 0, j = a.length - 1; i <= j; i++) {
          if (j == 1 || j == 5 || j == 9) { //两位数 处理特殊的 1*
            if (i == 0) {
              if (a[i] != '1') s.push(t.chars.charAt(a[i]));
            } else {
              s.push(t.chars.charAt(a[i]));
            }
          } else {
            s.push(t.chars.charAt(a[i]));
          }
          if (i != j) {
            s.push(t.units.charAt(j - i));
          }
        }
      }
      //return s;
      return s.join('').replace(/零([十百千万亿@#%^&~])/g, function (m, d, b) { //优先处理 零百 零千 等
        b = t.units.indexOf(d);
        if (b != -1) {
          if (d == '亿') return d;
          if (d == '万') return d;
          if (a[j - b] == '0') return '零'
        }
        return '';
      }).replace(/零+/g, '零').replace(/零([万亿])/g, function (m, b) { // 零百 零千处理后 可能出现 零零相连的 再处理结尾为零的
        return b;
      }).replace(/亿[万千百]/g, '亿').replace(/[零]$/, '').replace(/[@#%^&~]/g, function (m) {
        return {
          '@': '十',
          '#': '百',
          '%': '千',
          '^': '十',
          '&': '百',
          '~': '千'
        } [m];
      }).replace(/([亿万])([一-九])/g, function (m, d, b, c) {
        c = t.units.indexOf(d);
        if (c != -1) {
          if (a[j - c] == '0') return d + '零' + b
        }
        return m;
      });
    }
  }
};

module.exports = {

  /**
   * 设置是否隐藏loading标志
   */
  setHideLoading: function (val) {
    _hide_loading = val;
  },

  /**
   * 隐藏下一次远程请求的loading
   */
  isHideLoading: function () {
    return _hide_loading
  },

  /**
   * 格式化日期 
   */
  formatTime: formatTime,

  /**
   * 计算两个经纬度之间的距离
   */
  distance: distance,

  /**
   * 小于10的格式化函数
   */
  timeFormat: timeFormat,

  /**
   * 倒计时函数
   * @param openTeamTime 开始时间
   * @param duration //持续时间
   */
  countDown: countDown,
  /**
   * 倒计时函数
   * @param openTeamTime 开始时间
   * @param duration //持续时间
   */
  countDownDay: countDownDay,
  /**
   * 处理 Access Token 已过期
   */
  handleLoginStatus: handleLoginStatus,
  /**
   *  数字转中文  
   */
  numberConversion: numberConversion,
  /**
   * 时间戳转时间
   */
  timestampToTime: timestampToTime
}
